<template>
  <view class="edit-container">
    <!-- 顶部导航栏 -->
    <view class="action-bar">
      <uni-icons type="arrowleft" size="24" color="#5c3c1c" @click="goBack" />
      <text class="title">编辑商品</text>
    </view>
    
    <!-- 编辑表单 -->
    <uni-forms ref="form" :model="formData" :rules="rules">
      <!-- 商品名称 -->
      <uni-forms-item label="商品名称" required name="name">
        <uni-easyinput v-model="formData.name" placeholder="请输入商品名称" />
      </uni-forms-item>
      
      <!-- 价格输入 -->
      <uni-forms-item label="价格(元)" required name="price">
        <uni-easyinput 
          type="digit"
          v-model="priceYuan"
          placeholder="请输入价格"
          @input="updatePrice"
        />
      </uni-forms-item>
      
      <!-- 分类选择 -->
      <uni-forms-item label="分类" required name="category">
        <uni-data-select 
          v-model="formData.category"
          :localdata="categories"
        />
      </uni-forms-item>
      
      <!-- 材质选择 -->
      <uni-forms-item label="材质" required name="material">
        <uni-data-select 
          v-model="formData.material"
          :localdata="materials"
        />
      </uni-forms-item>
      
      <!-- 封面图 -->
      <uni-forms-item label="封面图" required name="cover">
        <uni-file-picker 
          v-model="coverFiles"
          fileMediatype="image"
          limit="1"
          @success="uploadSuccess"
        />
        <image v-if="formData.cover" :src="formData.cover" class="cover-preview" mode="aspectFit" />
      </uni-forms-item>
      
      <!-- 商品描述 -->
      <uni-forms-item label="商品描述" name="description">
        <uni-easyinput 
          type="textarea"
          v-model="formData.description" 
          placeholder="请输入商品详细描述"
          class="description-textarea"
        />
      </uni-forms-item>
      
      <!-- 上架状态 -->
      <uni-forms-item label="上架状态">
        <switch :checked="formData.status" @change="(e) => formData.status = e.detail.value" />
      </uni-forms-item>
      
      <!-- 提交按钮 -->
      <button type="primary" @click="submit" class="submit-btn">保存修改</button>
    </uni-forms>
  </view>
</template>

<script>
export default {
  data() {
    return {
      categories: [
        { value: '沙发', text: '沙发' },
        { value: '餐桌椅', text: '餐桌椅' },
        { value: '床具', text: '床具' },
        { value: '柜架', text: '柜架' },
        { value: '茶几', text: '茶几' },
        { value: '办公家具', text: '办公家具' }
      ],
      materials: [
        { value: '紫檀', text: '紫檀' },
        { value: '黄花梨', text: '黄花梨' },
        { value: '红酸枝', text: '红酸枝' },
        { value: '鸡翅木', text: '鸡翅木' },
        { value: '乌木', text: '乌木' }
      ],
      formData: {
        _id: '',
        name: '',
        price: 0,
        category: '',
        material: '',
        cover: '',
        description: '',
        status: true
      },
      priceYuan: '0.00',
      coverFiles: [],
      
      // 表单验证规则
      rules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入商品名称'
          }]
        },
        price: {
          rules: [{
            required: true,
            errorMessage: '请输入价格'
          }, {
            format: 'number',
            errorMessage: '价格必须是数字'
          }]
        },
        category: {
          rules: [{
            required: true,
            errorMessage: '请选择分类'
          }]
        },
        material: {
          rules: [{
            required: true,
            errorMessage: '请选择材质'
          }]
        },
        cover: {
          rules: [{
            required: true,
            errorMessage: '请上传封面图'
          }]
        }
      }
    }
  },
  onLoad(options) {
    if (options.id) {
      this.loadData(options.id);
    }
  },
  methods: {
    // 加载商品数据
    async loadData(id) {
      try {
        uni.showLoading({ title: '加载中...' });
        
        const db = uniCloud.database();
        const res = await db.collection('goods').doc(id).get();
        
        if (res.result.data) {
          this.formData = res.result.data;
          
          // 将价格转换为元显示
          if (this.formData.price) {
            this.priceYuan = (this.formData.price / 100).toFixed(2);
          }
          
          // 初始化封面图文件列表
          if (this.formData.cover) {
            this.coverFiles = [{ url: this.formData.cover }];
          }
        } else {
          throw new Error('商品不存在');
        }
      } catch (e) {
        console.error('加载失败:', e);
        uni.showToast({
          title: e.message || '加载商品失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 更新价格（元转分）
    updatePrice(value) {
      this.formData.price = value ? Math.round(parseFloat(value) * 100) : null;
    },
    
    // 图片上传成功处理
    uploadSuccess(e) {
      console.log('上传成功:', e);
      if (e.tempFilePaths && e.tempFilePaths.length > 0) {
        this.formData.cover = e.tempFilePaths[0];
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 提交表单
    async submit() {
      try {
        // 表单验证
        const validate = await this.$refs.form.validate();
        if (!validate) return;
        
        uni.showLoading({ title: '保存中...' });
        
        // 更新数据
        const db = uniCloud.database();
        const res = await db.collection('goods').doc(this.formData._id).update(this.formData);
        
        if (res.result && res.result.updated === 1) {
          uni.showToast({
            title: '更新成功',
            icon: 'success'
          });
          
          // 延迟返回
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error('更新失败');
        }
      } catch (e) {
        console.error('更新失败:', e);
        uni.showToast({
          title: e.message || '更新商品失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  }
}
</script>

<style scoped>
.edit-container {
  padding: 30rpx;
  background-color: #f8f3ed;
  min-height: 100vh;
}

.action-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #5c3c1c;
  margin-left: 20rpx;
}

.description-textarea {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: white;
}

.cover-preview {
  width: 200rpx;
  height: 200rpx;
  margin-top: 20rpx;
  border-radius: 8rpx;
  border: 1rpx solid #e8c39e;
}

.submit-btn {
  margin-top: 40rpx;
  background-color: #5c3c1c;
  color: white;
  border-radius: 8rpx;
  height: 80rpx;
  line-height: 80rpx;
}
</style>